package axio.sdf.combined;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.omg.CORBA.portable.RemarshalException;

public class Combine {

	public void CombinedFile(String path, int combinednumber) {

		BufferedReader br = null;

		try {

			String sCurrentLine;
			StringBuffer write_string = new StringBuffer();

			File file = new File(path.substring(0,path.lastIndexOf("_"))+"_combination_of_" + combinednumber+"_files.sdf");
			FileWriter fileWritter = new FileWriter(file, true);
			BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
			
			System.out.println("\nS t a r t e d  t o  C o m b i n e d . . . ");
			
			
			for(int i=1;i<=combinednumber;i++){
				 
				String openFile = path.substring(0,path.lastIndexOf("-")+1) + i + ".sdf";
			
				br = new BufferedReader(new FileReader(openFile));
				
				while ((sCurrentLine = br.readLine()) != null) {
					
					if (!file.exists()) {
						file.createNewFile();
					}
					
					write_string.append(sCurrentLine).append("\r\n");
				}
				
				
				bufferWritter.write(write_string.toString());
				write_string = null;
				write_string = new StringBuffer();
				sCurrentLine = null;
				if (br != null){
					br.close();
				}
			}
			
			bufferWritter.close();

			System.out.println("\n C o m b i n e d  "+combinednumber+"  o f  f i l e s . . . ");

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}

	}
}